package com.bestcem.xm.member.controller;

import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.member.entity.mongo.Footprint;
import com.bestcem.xm.member.entity.mongo.Member;
import com.bestcem.xm.member.enums.FootprintTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 只使用一次，不分层
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/1 11:20
 */
@Slf4j
@RestController
@RequestMapping("/member/footPrint")
public class InitFootPrintController {
    @Resource
    private RedisService redisService;

    private static final String INIT_KEY = "MEMBER_FOOTPRINT_INITDATA_KEY";

    @AuthIgnore
    @GetMapping("/initData")
    public XmResultJson<String> initData(Integer batchCount) {
        if (Objects.isNull(batchCount)) {
            batchCount = 20000;
        }

        RLock lock = redisService.getLock(INIT_KEY);
        // 预计执行200s左右，最长预计12分钟不到，设置为720s超时
        try {
            if (lock.tryLock(3, 720, TimeUnit.SECONDS)) {
                try {
                    String errmsg = run(batchCount);
                    if (StringUtils.isNotEmpty(errmsg)) {
                        return XmResultJson.fail(-1, errmsg);
                    }
                    return XmResultJson.success("SUCCESS");
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            log.error("中断异常");
        }
        return XmResultJson.fail(-1, "当前已在处理过程中，无法重复执行操作");
    }

    public String run(Integer batchCount) {

        try {
            boolean exists = true;
            // mongoTemplate.exists(new Query(criteria), CollectionConstant.FOOTPRINT);
            if (exists) {
                return "当前已有联系人足迹点数据，请清空联系人足迹点数据后再操作";
            }
            log.error("[MEMBER.footprint]数据导入执行开始");

            // 查询总数，获取页数
            Long total = 0L;
            // mongoTemplate.count(new Query(), CollectionConstant.MEMBER);
            int size = total.intValue() / batchCount;
            if (total.intValue() % batchCount != 0) {
                size++;
            }

            // 设置固定值
            Integer type = FootprintTypeEnum.MEMBER.getIndex();
            String content = "{\"title\":\"成为联系人\"}";

            log.error("[MEMBER.footprint]数据总数 {} 每批次处理数据 {}", total, batchCount);
            int start = 0;
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < size; i++) {
                log.error("[MEMBER.footprint]数据总循环次数 {} 当前次数 {}", size, i + 1);
                List<Member> memberList = null;
                // mongoTemplate.find(query, Member.class, CollectionConstant.MEMBER);

                List<Footprint> list = new ArrayList<>(memberList.size());
                for (Member m : memberList) {
                    Footprint fp = new Footprint();
                    fp.setOrgId(m.getOrgId());
                    fp.setMemberId(m.getId());
                    fp.setType(type);
                    fp.setSourceKey(m.getId());
                    fp.setContent(content);
                    fp.setFootprintTime(m.getCreateTime());
                    fp.setCreateTime(DateUtil.getCommonDate());
                    fp.setUpdateTime(fp.getCreateTime());
                    list.add(fp);
                }
                // mongoTemplate.insert(list, CollectionConstant.FOOTPRINT);

                start += batchCount;
            }
            long endTime = System.currentTimeMillis();
            log.error("[MEMBER.footprint]数据处理完成 总耗时：{} 秒", (endTime - startTime) / 1000);
        } catch (Exception e) {
            String errmsg = String.format("[MEMBER.footprint]数据处理失败 e:[%s]", e.toString());
            log.error(errmsg);
            return errmsg;
        }
        return null;
    }

}
